package com.newlink.building.record.fragment

import android.os.Looper
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.newlink.building.common_base.base.BaseMvpFragment
import com.newlink.building.common_base.event.RecordReadCountActionEvent
import com.newlink.building.common_base.ext.setNewOrAddData
import com.newlink.building.common_base.model.bean.CallRecordListData
import com.newlink.building.common_base.model.bean.RecordMessageReadRequest
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.WeakHandler
import com.newlink.building.NL_App
import com.newlink.building.record.R
import com.newlink.building.record.adapter.Module_Record_CallRecordAdapter
import com.newlink.building.record.databinding.FragmentCallRecordBinding
import com.newlink.building.record.mvp.Module_Record_CallRecordPresenter
import com.newlink.building.record.mvp.contract.Module_Record_CallRecordContract
import org.greenrobot.eventbus.EventBus

/**
 * @author wangyang
 * @date 2022/9/29
 * @description 记录——呼叫记录页面
 */
class Module_Record_CallRecordFragment :
    BaseMvpFragment<Module_Record_CallRecordContract.View, Module_Record_CallRecordContract.Presenter>(),
    Module_Record_CallRecordContract.View {

    private val weakHandler by lazy { WeakHandler(Looper.getMainLooper()) }
    private var curList: MutableList<CallRecordListData> = ArrayList()
    private var curPage: Int = 1
    private var curLimit: Int = 20
    private var mAdapter: Module_Record_CallRecordAdapter? = null
    private var isRefreshLayoutRequest: Boolean = false
    private var empty_content: View? = null

//    override fun attachLayoutRes(): Int {
//        return R.layout.fragment_call_record
//    }

    private lateinit var mBinding: FragmentCallRecordBinding
    override fun attachLayoutRes(): View {
        mBinding = FragmentCallRecordBinding.inflate(layoutInflater)
        return mBinding.root
    }


    override fun initView(view: View) {
        empty_content = view.findViewById(R.id.empty_content)
        mBinding.swipeRefreshLayout.setOnRefreshListener {
            isRefreshLayoutRequest = true
            weakHandler.postDelayed({
                curPage = 1
                lazyLoad()
            }, 500)
        }
        mAdapter = Module_Record_CallRecordAdapter(curList, agoraId.toString())
        mBinding.rvCallRecord.adapter = mAdapter
        // 当前版本 取消call log 点击 T70346
//        mAdapter?.setOnItemClickListener { adapter, view, position ->
//            val curData = curList[position]
//            if (curData.callerIdNumber == sipInforData.sipAccount) {
//                if (!TextUtils.isEmpty(curData.name)) {
//                    VoipController.get().makeAudioCall(curData.destinationNumber, curData.name)
//                } else if (!TextUtils.isEmpty(curData.deviceName)) {
//                    VoipController.get()
//                        .makeVideoCall(curData.destinationNumber, curData.deviceName)
//                }
//            } else {
//                if (!TextUtils.isEmpty(curData.name)) {
//                    VoipController.get().makeAudioCall(curData.callerIdNumber, curData.name)
//                } else if (!TextUtils.isEmpty(curData.deviceName)) {
//                    VoipController.get().makeVideoCall(curData.callerIdNumber, curData.deviceName)
//                }
//            }
//
//        }

        mAdapter?.run {
            setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn)
            loadMoreModule.setOnLoadMoreListener {
                isRefreshLayoutRequest = false
                ++curPage
                showLoading()
                weakHandler.postDelayed({ lazyLoad() }, 500)
            }
        }
    }

    override fun lazyLoadDataIfPrepared() {
    }

    override fun lazyLoad() {
        NLog.e("CallRecordFragment lazyLoad")
        mPresenter?.getCallRecordList(accessToken, curPage, curLimit, sipInforData.sipAccount)
    }

    override fun onResume() {
        super.onResume()
        curPage = 1
    }

    override fun showLoading() {
        mBinding.swipeRefreshLayout.isRefreshing = true
    }

    override fun hideLoading() {
        isRefreshLayoutRequest = false
        mBinding.swipeRefreshLayout.isRefreshing = false
    }

    override fun createPresenter(): Module_Record_CallRecordContract.Presenter = Module_Record_CallRecordPresenter()

    override fun getCallRecordListSuccess(total: Int, list: MutableList<CallRecordListData>?) {
        readMissedCalls()
        if (isRefreshLayoutRequest) {
//            showToast(getString(R.string.default_list_data_refresh))
            hideLoading()
            curList?.clear()
        }

        list?.let {
            if (curPage == 1) {//加载第一页
                NLog.e("is first page,set new data")
                curList.clear()
                curList = it
                mAdapter?.setNewOrAddData(true, list)
            } else {//不是第一页,则添加数据
                NLog.e("current page is $curPage,add data")
                curList.addAll(it)
                mAdapter?.setNewOrAddData(false, list)
            }
        }
        NLog.e("display size:${curList.size} total:$total pageNum:$curPage ")
        //小于总条数,继续加载更多,否则停止加载更多
        if (curList.size < total) {
            mAdapter?.loadMoreModule?.loadMoreComplete()
        } else {
            mAdapter?.loadMoreModule?.loadMoreEnd()
        }

        if (curList == null || curList?.size == 0) {
            empty_content?.visibility = View.VISIBLE
            mBinding.rvCallRecord.visibility = View.GONE
        } else {
            empty_content?.visibility = View.GONE
            mBinding.rvCallRecord.visibility = View.VISIBLE
        }
    }

    override fun getCallRecordListFail() {
    }

    override fun readMissedCallsSucess(success: Boolean) {
        if (success) {
            var event = (parentFragment as Module_Record_RecordFragment).initialReadCountEvent
            if (event != null) {
                EventBus.getDefault()
                    .post(RecordReadCountActionEvent(event.logOpen, logCall = 0, event.security))
            } else {
                EventBus.getDefault().post(RecordReadCountActionEvent(logCall = 0))
            }
        }
    }

    override fun onVisible() {
        super.onVisible()
        lazyLoad()
        NL_App.coreContext.apply {
            notificationsManager.dismissMissedCallNotification()
            core.resetMissedCallsCount()
        }
    }

    private fun readMissedCalls() {
        mPresenter?.readMissedCalls(
            accessToken,
            RecordMessageReadRequest(projectId.toLongOrNull() ?: 0L, 2, null)
        )
    }
}